import dotenv from "dotenv";
import { MongoClient } from "mongodb";
import { fileURLToPath } from "url";
import path from "path";

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载环境变量
dotenv.config({ path: path.join(__dirname, "../.env") });

const MONGODB_URI = process.env.MONGODB_URI;
const DB_NAME = process.env.DB_NAME || "login-system";

// 数据库迁移脚本：移除客户表中的旧字段
async function removeOldFields() {
  let client;

  try {
    // 连接数据库
    client = new MongoClient(MONGODB_URI);
    await client.connect();
    console.log("数据库连接成功");

    const db = client.db(DB_NAME);
    const customersCollection = db.collection("customers");

    // 移除旧字段：alipay, bankCard, bankName
    const result = await customersCollection.updateMany(
      {},
      {
        $unset: {
          alipay: "",
          bankCard: "",
          bankName: "",
        },
      }
    );

    console.log(`成功移除 ${result.modifiedCount} 个客户记录的旧字段`);

    // 为客户表添加新字段的默认值（如果不存在）
    const updateResult = await customersCollection.updateMany(
      { prepaidAmount: { $exists: false } },
      {
        $set: {
          prepaidAmount: 0,
          transactionMethods: [],
          shippingAddresses: [],
        },
      }
    );

    console.log(
      `成功为 ${updateResult.modifiedCount} 个客户记录添加新字段默认值`
    );

    console.log("迁移完成");
  } catch (error) {
    console.error("迁移失败:", error);
  } finally {
    if (client) {
      await client.close();
      console.log("数据库连接已关闭");
    }
    process.exit(0);
  }
}

// 运行迁移
removeOldFields();
